<?php
namespace backend\controllers;

use Yii;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    public function behaviors()
    {
        return [];
    }


    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        $session = Yii::$app->session;
        $admin_id = $session->get('admin_id');
        if(!$admin_id)
        {
            return $this->redirect(array('site/login'));
        }
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        $request = Yii::$app->request;
        if($request->isPost)
        {
            $name = $request->post('name');
            $password = $request->post('password');
            $query = (new \yii\db\Query())
                ->select(['id','name','password'])
                ->from('admin')
                ->where(['name'=>$name,'is_usable'=>1])
                ->one();
            if (md5($password) == $query['password']) {
                $session = Yii::$app->session;
                $session->set('admin_id',$query['id']);
                $session->set('admin_name',$query['name']);
                return $this->goHome();exit;
            }
        }
            return $this->render('login');
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        $session = Yii::$app->session;
        $session->remove('admin_id');
        $session->remove('admin_name');

        return $this->redirect(array('site/login'));
    }
}
